package com.sorted.bridge;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;

import com.sorted.SortBusiness;

import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class SortCocosBridge {

    private static SortCocosBridge callbackApi;
    public static WeakReference<Activity> mainGameActivity;
    private Method evalString;
    private Method runOnGLThread;

    public static SortCocosBridge getInstance() {
        if (callbackApi == null) {
            callbackApi = new SortCocosBridge();
        }
        return callbackApi;
    }

    public void setMainGameActivity(Activity activity) {
        mainGameActivity = new WeakReference<>(activity);

    }

    private static final Handler handler = new Handler(Looper.getMainLooper());
    public void XSSdkCallback(String action, String jsonData) {
        if (mainGameActivity == null ||  mainGameActivity.get() == null) {
            return;
        }
        handler.post(() -> {
            if (runOnGLThread==null){
                try {
                    Class clzCocos2dAct = Class.forName(SortBusiness.COCOS2DX_ACTIVITY_PATH, false, SortBusiness.context.getClassLoader());
                    runOnGLThread = clzCocos2dAct.getDeclaredMethod("runOnGLThread", Runnable.class);
                    runOnGLThread.setAccessible(true);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            try {
                check();
                callback(action,jsonData);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void callback(String action, String jsonData) throws InvocationTargetException, IllegalAccessException {
        runOnGLThread.invoke(mainGameActivity.get(), (Runnable) () -> {
            try {
                evalString.invoke(null, String.format("window.AdCallback('%s','%s')", action, jsonData));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void check() {

        if (evalString == null){
            try {
                Class clzBridge = Class.forName(SortBusiness.COCOS2DX_JJB_PATH, false, SortBusiness.context.getClassLoader());
                evalString = clzBridge.getDeclaredMethod("evalString", String.class);
                evalString.setAccessible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
